package com.cskaoyan.service;

import com.cskaoyan.bean.Ad;
import com.cskaoyan.bean.AdExample;
import com.cskaoyan.bean.User;
import com.cskaoyan.bean.basebean.BasePageData;
import com.cskaoyan.bean.basebean.BaseParam;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.bean.user.AddressExample;
import com.cskaoyan.exception.AddressException;
import com.cskaoyan.mapper.AddressMapper;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author lxy
 * @create 2021-10-21 11:24
 */
@Service
public class AddressServiceImpl implements  AddressService {

    @Autowired
    AddressMapper addressMapper;

    @Override
    public Address detailAddress(Integer id) {

        Address address = addressMapper.selectByPrimaryKey(id);

        return address;
    }

    @Override
    public void updateAddress(Address address) {
        address.setUserId(getUserId());
        address.setUpdateTime(new Date(System.currentTimeMillis()));
        if (address.getIsDefault() == true) {
            Integer i = addressMapper.selectByUserId(getUserId());
            if (i != null) {
                addressMapper.updateNotDefault(i);
            }
        }
        addressMapper.updateByPrimaryKeySelective(address);

    }

    @Override
    public void createAddress(Address address) {
        address.setUserId(getUserId());
        address.setAddTime(new Date(System.currentTimeMillis()));
        address.setUpdateTime(new Date(System.currentTimeMillis()));

        if (address.getIsDefault() == true) {
            Integer id = addressMapper.selectByUserId(getUserId());
            if (id != null) {
                addressMapper.updateNotDefault(id);
            }
        }
        addressMapper.insertSelective(address);
    }

    @Override
    public BasePageData queryAddressInWx(BaseParam baseParam) {
        AddressExample example = new AddressExample();
        AddressExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(getUserId());
        List<Address> addressList = addressMapper.selectByExample(example);

        return BasePageData.ok(addressList);
    }

    @Override
    public void deleteAddress(Integer id) throws AddressException {
        Integer i = addressMapper.updateDeleted(id);
        if (i == 0) throw new AddressException();
        return;
    }

    private Integer getUserId() {
        Subject subject = SecurityUtils.getSubject();
        User primaryPrincipal = (User) subject.getPrincipals().getPrimaryPrincipal();
        return primaryPrincipal.getId();
    }

}
